<?php
function createNewTempContact() {
	global $dbname, $db, $db_selected;
	
	// Clear any existing temp entries for this user
	deleteTempContacts();
	
	/*
	 * Get last Contact ID Number (IDNumber)
	 */
	$sql = "SELECT MAX(IDNumber) AS MaxID from cdc_Contacts WHERE OrgFlag = '".$_SESSION['org']."'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	$maxContactID = $row['MaxID'];
	$newContactID = $maxContactID+1;
	
	// Create new temp entry in cdc_Contacts
	$sql = "INSERT into cdc_Contacts (
			IDNumber,
			DateofContact,
			Status,
			Temp,
			OrgFlag,
			DateUpdate,
			UseridEntry
			) values (
			'$newContactID',
			'".date('Y-m-d G:i:s')."',
			'1',
			'1',
			'".$_SESSION['org']."',
			'".date('Y-m-d')."',
			'".$_SESSION['userid']."'
			)";
	$result = mysql_db_query($dbname,$sql);
	
	// Retrieve entry ID
	$entryID        = mysql_insert_id();
	$contactID      = $newContactID;	
	$contactIDArray = array($entryID,$contactID);
	return $contactIDArray;
}

function deleteTempContacts() {
	global $dbname, $db, $db_selected;
			
	/*
	 * Now, delete contact entries
	 */	
	$sql = "DELETE from cdc_Contacts
			WHERE UseridEntry = '".$_SESSION['userid']."' AND Temp = 1";
	$result = mysql_db_query($dbname,$sql);	
}

function saveSubject($subjectString,$contactID) {
	global $dbname, $db, $db_selected;
	
	$subjectString = trim($subjectString);
	if (!empty($subjectString)) {	
		$subjectString = fieldToDB($subjectString);
		$sqlUpdateSubject = "UPDATE cdc_Contacts SET 
								SubjectLine = '$subjectString',
								Temp = 0
								WHERE ContactID = $contactID";
		$resultUpdateSubject = mysql_db_query($dbname,$sqlUpdateSubject);
	}	
	return 1;
}

/*
 * RESOURCE REFERRAL ITEMS
 */

function getEventReferrals($contactID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_linkContactEvent WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);

	$stringJSON   = '({"EventIDs":[';
	
	while ($value = mysql_fetch_assoc($result)) {
		$newArray = array(
						'EventID' => $value['EventID']
					);
		$stringJSON .= Zend_Json::encode($newArray).',';
	}	
	$stringJSON = substr($stringJSON,0,-1);
	$stringJSON .= ']})';
	return $stringJSON;
}

function toggleReferralItem($referralColumn,$contactID) {
	global $dbname, $db, $db_selected;
	
	/*
	 * What state is the column currently?
	 */
	
	$sqlCheck = "SELECT $referralColumn from cdc_Contacts WHERE ContactID = $contactID";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	$rowCheck = mysql_fetch_assoc($resultCheck);
	$stateCheck = $rowCheck[$referralColumn];

	if ($stateCheck == 1) {
		$newState = 0;
	} else {
		$newState = 1;
	}
	
	$sqlUpdate = "UPDATE cdc_Contacts SET 
					$referralColumn = $newState
					WHERE ContactID = $contactID";
	$resultUpdate = mysql_db_query($dbname,$sqlUpdate);
	if ( ($newState == 0) && ($referralColumn == 'ReferralFollowUp') ) {
		/*
		 * Delete any records from cdc_linkStaffContactFollowUp
		 */
		$sql = "DELETE from cdc_linkStaffContactFollowUp WHERE ContactID = '$contactID'";
		$result = mysql_db_query($dbname,$sql);
	}
	return 1;
}

function saveCareNotebookItems($contactID,$langString,$number=null) {
	global $dbname, $db, $db_selected;
	
	// Remove trailing | from langString
	$langString = substr($langString,0,-1);
	
	if ( empty($number) || !is_numeric($number) ) {
		$number = 0;
	}
	
	$sqlSave = "UPDATE cdc_Contacts SET
				ReferralCareNotebookLanguage = '$langString',
				ReferralCareNotebookNumber   = '$number'
				WHERE ContactID = $contactID";
	$resultSave = mysql_db_query($dbname,$sqlSave);
}

function saveBrochureItems($contactID,$type=null,$number=null) {
	global $dbname, $db, $db_selected;
	
	if ( empty($number) || !is_numeric($number) ) {
		$number = 0;
	}
	
	$sqlSave = "UPDATE cdc_Contacts SET
				ReferralBrochure       = '1',
				ReferralBrochureType   = '$type',
				ReferralBrochureNumber = '$number'
				WHERE ContactID = $contactID";
	$resultSave = mysql_db_query($dbname,$sqlSave);
}

function saveFollowUpItems($contactID,$selectedStaffString,$followUpNotes,$followUpEmail) {
	global $dbname, $db, $db_selected;
	$returnString = '';
	
	/*
	 * Clear existing follow up staff entries and notes for this contact
	 */
	$sqlClear0 = "SELECT MessageID from cdc_Messages WHERE ContactID = $contactID AND FollowUpID > 0";
	$resultClear0 = mysql_db_query($dbname,$sqlClear0);
	
	$sqlClear1 = "DELETE from cdc_Messages WHERE ContactID = $contactID AND FollowUpID > 0";
	$resultClear1 = mysql_db_query($dbname,$sqlClear1);	
	
	$sqlClear2 = "DELETE from cdc_ContactFollowUp WHERE ContactID = $contactID";
	$resultClear2 = mysql_db_query($dbname,$sqlClear2);
	
	while ($valueClear0 = mysql_fetch_assoc($resultClear0)) {
		$messageID = $valueClear0['MessageID'];
		$sqlClear3 = "DELETE from cdc_linkMessageStaff WHERE MessageID = '$messageID'";
		$resultClear3 = mysql_db_query($dbname,$sqlClear3);
	}

	/*
	 * Enter selected staff members into cdc_linkStaffContactFollowUp
	 */
	$staffIDArray = explode('|',$selectedStaffString);
	$staffEmailArray = array();
	for($a=0;$a<=(count($staffIDArray)-1);$a++) {
		$staffID = $staffIDArray[$a];
		
		// Retrieve staff member email address
		if (!empty($staffID)) {
			$sqlEmail = "SELECT StaffEmail from cdc_Users WHERE StaffID = $staffID";
			$resultEmail = mysql_db_query($dbname,$sqlEmail);
			$rowEmail = mysql_fetch_assoc($resultEmail);
			$staffEmail = $rowEmail[StaffEmail];
			$staffEmailArray[$a] = $staffEmail;		

			$sqlAddStaffFollowUp = "INSERT into cdc_linkStaffContactFollowUp (
                                    StaffID,
                                    ContactID
                                    ) values (
                                    '$staffID',
                                    '$contactID'
                                    )";
            $resultAddStaffFollowUp = mysql_db_query($dbname,$sqlAddStaffFollowUp);
		}	
	}
		
	$followUpNotes = fieldToDB($followUpNotes);
	/*
	 * Convert comma delimited email addresses to PHP array
	 */	
	$additionalEmailArray = commaDelEmailToArray($followUpEmail);
	
	/*
	 * Check for valid email addresses
	 */ 
	$emailValidator = new Zend_Validate_EmailAddress();
	$goodEmailString = '';
	$goodAdditionalEmailArray = array();
	$error = 0;
	if (!empty($followUpEmail)) {
		$a=0;
		foreach($additionalEmailArray as $additionalEmailAddress) {	
			if ($emailValidator->isValid($additionalEmailAddress)) {
			    // email appears to be valid\
				$goodEmailString .= $additionalEmailAddress.',';
				$goodAdditionalEmailArray[$a] = $additionalEmailAddress;
				$a++;				
			} else {
			    // email is invalid; print the reasons
			    $returnString .= $additionalEmailAddress.' ';
			    $error = 1;
			}
		}
		// Remove trailing ,
		$goodEmailString = substr($goodEmailString,0,-1);
	}	
	/*
	 * Merge 2 email arrays and send email notification
	 */
	$completeEmailArray = array_merge($staffEmailArray,$goodAdditionalEmailArray);
	sendContactFollowUpEmail($completeEmailArray,$followUpNotes,$contactID);	
		
	/*
	 * INSERT follow up info and email addresses
	 */
	$sqlFollowUp = "INSERT into cdc_ContactFollowUp (
					ContactID,
					AdditionalRecipients,
					DateUpdate,
					Userid
					) values (
					'$contactID',
					'$goodEmailString',
					'".date('Y-m-d')."',
					'".$_SESSION['userid']."'
					)";
	$resultFollowUp = mysql_db_query($dbname,$sqlFollowUp);
	$followUpID = mysql_insert_id();
	
	/*
	 * INSERT follow-up message
	 */
	$sqlMessage = "INSERT into cdc_Messages (
					Message,
					ContactID,
					FollowUpID,
					DateEntry,
					DateUpdate,
					Userid
					) values (
					'$followUpNotes',
					'$contactID',
					'$followUpID',
					'".date('Y-m-d G:i:s')."',
					'".date('Y-m-d')."',
					'".$_SESSION['userid']."'
					)";
	$resultMessage = mysql_db_query($dbname,$sqlMessage);
	$messageID = mysql_insert_id();
	
	/*
	 * INSERT follow-up staff members
	 */
	for($a=0;$a<=(count($staffIDArray)-1);$a++) {
		$staffID = $staffIDArray[$a];
		
		if ($staffID>0) {
			$sqlAddStaffFollowUp = "INSERT into cdc_linkMessageStaff (
								MessageID,
								StaffID
								) values (
								'$messageID',
								'$staffID'
								)";
			$resultAddStaffFollowUp = mysql_db_query($dbname,$sqlAddStaffFollowUp);
		}			
	}	
	
	/*
	 * Update contact status
	 */
	$sql = "UPDATE cdc_Contacts SET Status = 2 WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
		
	return $error.'|'.$returnString;	
}

function getFollowUpInformation($contactID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT StaffID from cdc_linkMessageStaff MS
			LEFT JOIN 
				cdc_Messages M ON M.MessageID = MS.MessageID
			WHERE 
				M.ContactID = '$contactID' AND
				M.FollowUpID > 0";
	$result = mysql_db_query($dbname,$sql);
	
	$stringJSON   = '({"Staff":[';
	
	while ($value = mysql_fetch_assoc($result)) {
		$newArray = array(
						'StaffID' => $value['StaffID']
					);
		$stringJSON .= Zend_Json::encode($newArray).',';
	}	
	$stringJSON = substr($stringJSON,0,-1);
	$stringJSON .= ']})';
	$staffJSON = $stringJSON;
	
	/*
	 * Get other follow-up info
	 */
	$sql = "SELECT * from cdc_ContactFollowUp CF
			LEFT JOIN
				cdc_Messages M ON M.FollowUpID = CF.FollowUpID
			WHERE
				CF.ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	$rowFollowUpInfo = mysql_fetch_assoc($result);
	
	$followUpMessage = DBToField($rowFollowUpInfo['Message']);
	$rowFollowUpInfo['Message'] = $followUpMessage;
	$followUpJSON    = Zend_Json::encode($rowFollowUpInfo);
	
	return $staffJSON.'|'.$followUpJSON;
}

function saveReferralLinks($contactID,$urls=null) {
	global $dbname, $db, $db_selected;
	
	/*
	 * Parse up URLs and save them
	 */
	if (!empty($urls)) {
		/*
		 * Put URL's into Contact table
		 */
		$sql = "UPDATE cdc_Contacts SET ReferralLinkURL = '$urls' WHERE ContactID = $contactID";
		$result = mysql_db_query($dbname,$sql);
		
		$linkArray = explode(',',$urls);
		$i=0;
		foreach($linkArray as $link) {
			/*
			 * Is this link already in the database?
			 */
			$link = trim($link);
			if (!empty($link)) {
				$sqlCheck = "SELECT URLID from cdc_Links WHERE URL = '$link'";
				$resultCheck = mysql_db_query($dbname,$sqlCheck);
				if (mysql_num_rows($resultCheck)<1) {
					/*
					 * Put this link in the cdc_Links table
					 */
						$sqlNewLink = "INSERT into cdc_Links (
										URL,
										Referral,
										DateUpdate,
										Userid
										) values (
										'$link',
										'1',
										'".date('Y-m-d')."',
										'".$_SESSION['userid']."'
										)";
						$resultNewLink = mysql_db_query($dbname,$sqlNewLink);
				}
			}	
			$i++;
		}
	}
	return $urls; 
	
}

function saveReferralEvent($eventID=null,$eventIDString=null,$contactID) {
	global $dbname, $db, $db_selected;
	if (!empty($eventIDString)) {
		// Parse eventIDString
		$eventIDArray = explode('|',$eventIDString);
		/*
		 * Clear existing entries for this contactID
		 */
		$sql = "DELETE from cdc_linkContactEvent WHERE ContactID = '$contactID'";
		$result = mysql_db_query($dbname,$sql);
		
		$eIDs = count($eventIDArray);
		for($a=0;$a<=($eIDs-1);$a++) {
			$eventID = $eventIDArray[$a];
			if ($eventID>0) {
				$sql = "INSERT into cdc_linkContactEvent (
						ContactID,
						EventID
						) values (
						'$contactID',
						'$eventID'
						)";
				$result = mysql_db_query($dbname,$sql);
			}	
		}
	} elseif (!empty($eventID)) {
		$sql = "INSERT into cdc_linkContactEvent (
					ContactID,
					EventID
					) values (
					'$contactID',
					'$eventID'
					)";
		$result = mysql_db_query($dbname,$sql);
	}
}

function saveReferralLibraryItem($libraryID=null,$contactID=null) {
	global $dbname, $db, $db_selected;
	
	$sql = "INSERT into cdc_linkContactLibrary (
			ContactID,
			LibraryID,
			Userid,
			DateEntry
			) values (
			'$contactID',
			'$libraryID',
			'".$_SESSION['userid']."',
			'".date('Y-m-d')."'
			)";
	$result = mysql_db_query($dbname,$sql);
	return getLibraryItems($contactID,'contact');
}

/*
 * FAMILY/SUPPORT TEAM MEMBER ITEMS
 */

function saveMember($phpJSON,$contactID) {
	global $dbname, $db, $db_selected;
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	// Replace default items with null
	$phpArray = replaceDefaultValues($phpArray);	
	
	$tabID       = $phpArray['tabID'];
	$memberID    = $phpArray['memberID'];
	$familyID    = $phpArray['familyID'];
	$nameFirst   = fieldToDB($phpArray['nameFirst']);
	$nameLast    = fieldToDB($phpArray['nameLast']);
	$address     = fieldToDB($phpArray['address']);
	$city        = fieldToDB($phpArray['city']);
	$state       = $phpArray['state'];	
	$zip         = fieldToDB($phpArray['zip']);
	$county      = $phpArray['county'];
	$phone1      = fieldToDB($phpArray['phone1']);
	$phone2      = fieldToDB($phpArray['phone2']);
	$phone3      = fieldToDB($phpArray['phone3']);
	$phone4      = fieldToDB($phpArray['phone4']);
	$email       = fieldToDB($phpArray['email']);
	$email2      = fieldToDB($phpArray['email2']);
	$language    = $phpArray['language'];
	$ethnicity   = $phpArray['ethnicity'];
	$school      = fieldToDB($phpArray['school']);
	$schoolType  = $phpArray['schoolType'];
	$district    = $phpArray['district'];
	$okToContact = $phpArray['okToContact'];
	$gender      = $phpArray['gender'];	
	$memberType  = $phpArray['memberType'];
	$memberRole  = $phpArray['memberRole'];
	$childAgeYr  = $phpArray['childAgeYr'];
	$childAgeMo  = $phpArray['childAgeMo'];	
	$childDOB    = $phpArray['childDOB'];
	$profOrg     = fieldToDB($phpArray['profOrg']);
	$profURL     = fieldToDB($phpArray['profURL']);
	
	/*
	 * OrPTI Specific fields
	 */
	$profTitle            = fieldToDB($phpArray['profTitle']);
	$familyLowLiteracy    = $phpArray['familyLowLiteracy'];
	$familyLowIncome      = $phpArray['familyLowIncome'];
	$parentSingle         = $phpArray['parentSingle'];
	$okToContactPhoneHome = $phpArray['okToContactPhoneHome'];
	$okToContactPhoneWork = $phpArray['okToContactPhoneWork'];
	$okToContactEmail     = $phpArray['okToContactEmail'];
	
	if ($childAgeYr == 'Yr') {
		$childAgeYr = '';
	}
	if ($childAgeMo == 'Mo') {
		$childAgeMo = '';
	}
	$childAge    = $childAgeYr.'|'.$childAgeMo;
	
	if ($_SESSION['org'] == 'Swindells') {
		$orgSwindells = 1;
		$orgOrPTI     = 0;
	} else {
		$orgSwindells = 0;
		$orgOrPTI     = 1;
	}
		
	// Are we adding a new member or updating an existing member?
	if ($memberID == 0) {
		$sqlUpdateMember = "INSERT into cdc_ContactClientDemographics (
					FirstName,
					LastName,
					Address,
					City,
					State,
					Zip,
					County,
					Email1,
					Email2,
					Phone1,
					Phone2,
					Phone3,
					Phone4,
					Gender,
					MemberType,
					SingleParent,
					RoleIDs,
					ChildDOB,
					ChildAge,
					Ethnicity,
					PrimaryLanguage,
					OrganizationName,
					OrganizationTitle,
					OrganizationURL,
					TypeOfSchool,
					SchoolName,
					SchoolDistrict,
					MayContact,
					MayContactPhoneHome,
					MayContactPhoneWork,
					MayContactEmail,
					OrgSwindells,
					OrgOrPTI,
					DateUpdate,
					Userid
				) values (
					'$nameFirst',
					'$nameLast',
					'$address',
					'$city',
					'$state',
					'$zip',
					'$county',
					'$email',
					'$email2',
					'$phone1',
					'$phone2',
					'$phone3',
					'$phone4',
					'$gender',
					'$memberType',
					'$parentSingle',
					'$memberRole',
					'$childDOB',
					'$childAge',
					'$ethnicity',
					'$language',
					'$profOrg',
					'$profTitle',
					'$profURL',
					'$schoolType',
					'$school',
					'$district',
					'$okToContact',
					'$okToContactPhoneHome',
					'$okToContactPhoneWork',
					'$okToContactEmail',
					'$orgSwindells',
					'$orgOrPTI',
					'".date('Y-m-d')."',
					'".$_SESSION['userid']."'
				)";
		$resultUpdateMember = mysql_db_query($dbname,$sqlUpdateMember);
		$memberID = mysql_insert_id();	
				
		/*
		 * Do we need a new familyID?
		 */
		if ($familyID == 0) {
			$familyID = getNextFamilyID();		
		}
		
		/*
		 * Associate familyID with memberID
		 */
		$sqlFamilyLink = "INSERT into cdc_linkMemberFamily (
							MemberID,
							FamilyID
							) values (
							'$memberID',
							'$familyID'
							)";
		$resultFamilyLink = mysql_db_query($dbname,$sqlFamilyLink);
		
		/*
		 * Associate member with contactID
		 */
		associateMemberContact($memberID,$contactID);
		
	} else {
		$sqlUpdateMember = "UPDATE cdc_ContactClientDemographics SET
						FirstName        = '$nameFirst',
						LastName         = '$nameLast',
						Address          = '$address',
						City             = '$city',
						State            = '$state',
						Zip              = '$zip',
						County           = '$county',
						Email1           = '$email',
						Email2           = '$email2',
						Phone1           = '$phone1',
						Phone2           = '$phone2',
						Phone3           = '$phone3',
						Phone4           = '$phone4',
						Gender           = '$gender',
						MemberType       = '$memberType',
						SingleParent     = '$parentSingle',
						RoleIDs          = '$memberRole',
						ChildDOB         = '$childDOB',
						ChildAge         = '$childAge',
						Ethnicity        = '$ethnicity',
						PrimaryLanguage  = '$language',
						OrganizationName = '$profOrg',
						OrganizationTitle= '$profTitle',
						OrganizationURL  = '$profURL',
						TypeOfSchool     = '$schoolType',
						SchoolName       = '$school',
						SchoolDistrict   = '$district',
						MayContact       = '$okToContact',
						MayContactPhoneHome = '$okToContactPhoneHome',
						MayContactPhoneWork = '$okToContactPhoneWork',
						MayContactEmail     = '$okToContactEmail',
						DateUpdate       = '".date('Y-m-d')."'
					WHERE 
					MemberID = '$memberID'";
		$resultUpdateMember = mysql_db_query($dbname,$sqlUpdateMember);
	}
	
	if ($_SESSION['org'] == 'OrPTI') {
		/**
		 * Enter $familyLowLiteracy  into cdc_ContactClientSchoolTrans table
		 * and $familyLowIncome into cdc_ContactClientFamily table
		 */
		
		$phpJSONSchool = '{"lowLit":"'.$familyLowLiteracy.'"}';
		$phpJSONFamily = '{"lowIncome":"'.$familyLowIncome.'"}';
		
		saveClientInfoSchoolTrans($phpJSONSchool,$memberID);
		saveClientInfoFamily($phpJSONFamily,$memberID);
	}
	$nameFull = $nameFirst.' '.$nameLast;
	return $tabID.'|'.$memberID.'|'.$familyID.'|'.$nameFull;
}

function deleteMember($memberID) {
	global $dbname, $db, $db_selected;
	
	/*
	 * Remove this members' information
	 */
	$sql = "DELETE from cdc_ContactClientDemographics WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Remove reference to this member in any contacts
	 */
	$sql = "DELETE from cdc_linkContactMember WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);	
	
	/*
	 * Remove reference to this member in cdc_linkMemberFamily
	 */
	$sql = "DELETE from cdc_linkMemberFamily WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);	
	
	/*
	 * Delete member Client Information
	 */
	// TODO: Delete client information when deleting member
	
	return 1;
}

function getMembersForAutocompleter($fieldText,$searchField,$tabID) {
	global $dbname, $db, $db_selected;
	$entry = fieldToDB($fieldText);
	/*
	 * Get all members LIKE $entry
	 */
	$orgField = 'Org'.$_SESSION['org'];
	$sql = "SELECT MemberID,FirstName,LastName 
			FROM cdc_ContactClientDemographics 
			WHERE
			$searchField LIKE '%$entry%' AND
			$orgField = 1 AND
			Deleted = 0";
	$result = mysql_db_query($dbname,$sql);
	$rows = mysql_num_rows($result);
	
	$returnString = '<ul>';
	$i=0;
	while ($value = mysql_fetch_assoc($result)) {
		$memberID  = $value['MemberID'];
		$firstName = $value['FirstName'];
		$lastName  = $value['LastName'];
		
		/*
		 * Retrieve family ID for this member
		 */
		$sqlFamilyID = "SELECT FamilyID from cdc_linkMemberFamily 
						WHERE MemberID = '$memberID'";
		$resultFamilyID = mysql_db_query($dbname,$sqlFamilyID);
		$rowFamilyID = mysql_fetch_assoc($resultFamilyID);
		$familyID = $rowFamilyID['FamilyID'];
		if (empty($familyID)) {
			$familyID = 0;
		}
		
		/*
		 * Get number of members in this family
		 */
		$sqlMembers = "SELECT COUNT(MemberID) AS Members from cdc_linkMemberFamily
						WHERE
						FamilyID = '$familyID'";
		$resultMembers = mysql_db_query($dbname,$sqlMembers);
		$rowMembers = mysql_fetch_assoc($resultMembers);
		$totalMembers = $rowMembers['Members'];
		
		if (($i % 2) > 0) { $class = 'blueRow'; }
		else { $class = ''; }	
		$nameString = $lastName.', '.$firstName;
		$returnString .= '<li class="'.$class.'">';
		$returnString .= '<div title="Import member information" class="usersButtonSingle" style="padding: 2px; float: left;" onClick="contactFormGetInfoObj.getMemberInformation('.$familyID.','.$memberID.','.$tabID.');"></div>';
		if ($totalMembers>0) {
			$returnString .= '<div title="Import family information" class="usersButtonGroup" style="width: 26px; padding: 2px; float: left;" onClick="contactFormGetInfoObj.getFamilyInformation('.$familyID.','.$tabID.');"></div>';
		} else {
			$returnString .= '<div style="width: 26px; float: left; padding: 2px;"></div>';
			$totalMembers = 'No';
		}
		$returnString .= '<div onClick="contactFormGetInfoObj.getMemberInformation('.$familyID.','.$memberID.','.$tabID.');" style="padding: 2px; float: left; width: 120px; cursor: pointer;"><span style="font-size: 1.2em;">'.$nameString.' </span></div><div style="float: left;"><span style="font-size: 1.2em;">('.$totalMembers.' family members)</span></div><div style="clear: left;"></div></li>';
		$i++;
	}
	$returnString .= '</ul>';
	
	echo $returnString;
}

function getMemberInformation($memberID,$tabID,$newFamilyID=null,$contactID=null,$assign=null) {
	global $dbname, $db, $db_selected;

	$sqlMemberInfo = "SELECT * from cdc_ContactClientDemographics
						WHERE
						MemberID = '$memberID'";
	$resultMemberInfo = mysql_db_query($dbname,$sqlMemberInfo);
	$rowMemberInfo = mysql_fetch_assoc($resultMemberInfo);

	if ($_SESSION['org'] == 'OrPTI') {
		/*
		 * Get Low Literacy and Low Income
		 */
		$sqlLL = "SELECT LowLit from cdc_ContactClientSchoolTrans
					WHERE 
					MemberID = '$memberID'";
		$resultLL = mysql_db_query($dbname,$sqlLL);
		$rowLL = mysql_fetch_assoc($resultLL);
		$lowLit = $rowLL['LowLit'];
		
		$sqlLI = "SELECT LowIncome from cdc_ContactClientFamily
					WHERE 
					MemberID = '$memberID'";
		$resultLI = mysql_db_query($dbname,$sqlLI);
		$rowLI = mysql_fetch_assoc($resultLI);
		$lowIncome = $rowLI['LowIncome'];
	}
		
	if (mysql_num_rows($resultMemberInfo)>0) {	
		/*
		 * Convert dates
		 */
		$rowMemberInfo['ChildDOB'] = mySQLToExt($rowMemberInfo['ChildDOB']);
		$rowMemberInfo['TabID'] = $tabID;
		
		if ($_SESSION['org'] == 'OrPTI') {
			$rowMemberInfo['LowLit']    = $lowLit;		
			$rowMemberInfo['LowIncome'] = $lowIncome;			
		}
		
		$rowMemberInfo = array_map('DBToField',$rowMemberInfo);
		
		$stringJSON = Zend_Json::encode($rowMemberInfo);
			
		/*
		 * Assign this member to this contactID
		 */
		if ($assign == 1) {
			associateMemberContact($memberID,$contactID);
		}	
		return $stringJSON;
	} else {
		return false;
	}
}

function getFamilyInformation($familyID,$tabID,$newFamilyID=null,$contactID=null) {
	global $dbname, $db, $db_selected;
	
	$sqlFamilyMembers = "SELECT * from cdc_linkMemberFamily
							WHERE
							FamilyID = '$familyID'";
	$resultFamilyMembers = mysql_db_query($dbname,$sqlFamilyMembers);
	if (mysql_num_rows($resultFamilyMembers)>0) {
		$stringJSON   = '({"Members":[';
		while ($value = mysql_fetch_assoc($resultFamilyMembers)) {
			$memberID = $value[MemberID];
			if (getMemberInformation($memberID,$tabID,0,$contactID,0)) {
				$stringJSON .= getMemberInformation($memberID,$tabID,0,$contactID,1).',';
			}					
		}
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';		
	} else {
		$stringJSON = 0;
	}	
	return $stringJSON;
}

function removeTeamMemberFromContact($contactID,$memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "DELETE from cdc_linkContactMember 
			WHERE 
			ContactID = '$contactID' AND 
			MemberID = '$memberID'";	
	$result = mysql_db_query($dbname,$sql);
	$membersLeft = getContactMembersInformation($contactID);
	return $membersLeft;
}

/*
 * CLIENT INFORMATION ITEMS
 */

function getClientInfoDiagnosis($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientDiagnosis
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$diagName1 = getDiagnosisName($rowClientInfo['DiagnosisID1']);
	$diagName2 = getDiagnosisName($rowClientInfo['DiagnosisID2']);
	$diagName3 = getDiagnosisName($rowClientInfo['DiagnosisID3']);
	
	$rowClientInfo['DiagnosisID1'] = $diagName1;
	$rowClientInfo['DiagnosisID2'] = $diagName2;
	$rowClientInfo['DiagnosisID3'] = $diagName3;
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function getClientInfoInsurance($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientInsurance
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function getClientInfoHealthcare($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientHealthcare
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function getClientInfoSocial($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientSocial
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function getClientInfoSchoolTrans($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientSchoolTrans
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function getClientInfoFamily($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientFamily
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function getClientInfoEvents($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT CAT.CatTitle,EM.RegistrationID,EM.Attended,EM.DateRegister,C.EventID,C.EventName,C.EventCat,C.EventDescription,C.StartDate,C.EndDate
			FROM cdc_linkEventMember EM
			LEFT JOIN cdc_Calendar C ON C.EventID = EM.EventID
			LEFT JOIN cdc_sysCategory CAT ON C.EventCat = CAT.CatID
			WHERE EM.MemberID = '$memberID'
			ORDER BY C.StartDate DESC";
	$result = mysql_db_query($dbname,$sql);
	$rows = mysql_num_rows($result);
	$stringJSON   = '({"MemberEvents":[';
		
	if ($rows>0) {
		while ($value = mysql_fetch_assoc($result)) {
			/*
			 * Convert dates
			 */
			$dateStart    = new Zend_Date($value['StartDate'], Zend_Date::ISO_8601, 'en_US');
			$newDateStart = $dateStart->toString('MMM d');
			if ($value['EndDate'] != '0000-00-00 00:00:00') {
				$dateEnd      = new Zend_Date($value['EndDate'], Zend_Date::ISO_8601, 'en_US');
				$newDateEnd   = $dateEnd->toString('MMM d');
			} else {
				$newDateEnd = '';
			}
			$value['StartDate'] = $newDateStart;
			$value['EndDate']  = $newDateEnd;
			
			$dateReg = new Zend_Date($value['DateRegister'], Zend_Date::ISO_8601, 'en_US');
			$newDateReg = $dateReg->toString('MMM d');
			$value['DateRegister'] = $newDateReg;
			$value['EventDescription'] = strip_tags(stripslashes($value['EventDescription']));
			
			$stringJSON .= Zend_Json::encode($value).',';	
		}
		$stringJSON = substr($stringJSON,0,-1);
	}
	$stringJSON .= ']})';	
		
	/*
	 * TODO: Retrieve events for this client
	 */
	return $stringJSON;
}

function getClientInfoOther($memberID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_ContactClientOther
			WHERE MemberID = '$memberID'";
	$result = mysql_db_query($dbname,$sql);
	$rowClientInfo = mysql_fetch_assoc($result);
	
	$rowClientInfo['Concerns'] = DBToField($rowClientInfo['Concerns']);
	$rowClientInfo['Response'] = DBToField($rowClientInfo['Response']);
	
	$stringJSON = Zend_Json::encode($rowClientInfo);	
	return $stringJSON;
}

function saveClientInfoDiagnosis($phpJSON,$memberID) {
	echo $phpJSON;
	global $dbname, $db, $db_selected;
	if ($memberID>0) {	
		// Decode JSON
		$phpJSON = urldecode(stripslashes($phpJSON));
		$phpArray = Zend_Json::decode($phpJSON);
		
		$diag1  = $phpArray[diag1];
		$diag2  = $phpArray[diag2];
		$diag3  = $phpArray[diag3];
		$concerns = fieldToDB($phpArray[challenges]);
		$response = fieldToDB($phpArray[response]);
		
		if ($diag1 == 'Select first diagnosis...') {
			$diag1 = '';
		} else {
			$diag1 = getDiagnosisID($diag1);
		}
		if ($diag2 == 'Select second diagnosis...') {
			$diag2 = '';
		} else {
			$diag2 = getDiagnosisID($diag2);	
		}
		if ($diag3 == 'Select third diagnosis...') {
			$diag3 = '';
		} else {
			$diag3 = getDiagnosisID($diag3);
		}
	
		/*
		 * Check for existing record for this memberID
		 */
		$sqlCheck = "SELECT EntryID from cdc_ContactClientDiagnosis
					 WHERE MemberID = '$memberID'";
		$resultCheck = mysql_db_query($dbname,$sqlCheck);
		
		if (mysql_num_rows($resultCheck)>0) {
			/*
			 * We are updating an existing record
			 */
			$sql = "UPDATE cdc_ContactClientDiagnosis
					SET
					DiagnosisID1 = '$diag1',
					DiagnosisID2 = '$diag2',
					DiagnosisID3 = '$diag3',
					PHCID      = '',
					Concerns   = '$concerns',
					Response   = '$response',
					DateUpdate = '".date('Y-m-d')."'
					WHERE MemberID = '$memberID'";
		} else {
			/*
			 * We are adding a new record
			 */
			$sql = "INSERT into cdc_ContactClientDiagnosis (
					MemberID,
					DiagnosisID1,
					DiagnosisID2,
					DiagnosisID3,
					PHCID,
					Concerns,
					Response,
					DateUpdate,
					Userid
					) values (
					'$memberID',
					'$diag1',
					'$diag2',
					'$diag3',
					'',
					'$concerns',
					'$response',
					'".date('Y-m-d')."',
					'".$_SESSION['userid']."'
					)";		
		}
		$result = mysql_db_query($dbname,$sql);
	}	
	return 0;
}

function saveClientInfoInsurance($phpJSON,$memberID) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$insPublic  = $phpArray['insPublic'];
	$insPrivate = $phpArray['insPrivate'];
	$insNone    = $phpArray['insNone'];
	$concerns   = fieldToDB($phpArray['insConcerns']);
	$response   = fieldToDB($phpArray['insResponse']);
		
	/*
	 * Check for existing record for this memberID
	 */
	$sqlCheck = "SELECT EntryID from cdc_ContactClientInsurance
				 WHERE MemberID = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	
	if (mysql_num_rows($resultCheck)>0) {
		/*
		 * We are updating an existing record
		 */
		$sql = "UPDATE cdc_ContactClientInsurance
				SET
				InsPublic  = '$insPrivate',
				InsPrivate = '$insPublic',
				InsNone    = '$insNone',
				Concerns   = '$concerns',
				Response   = '$response',
				DateUpdate = '".date('Y-m-d')."'
				WHERE MemberID = '$memberID'";
	} else {
		/*
		 * We are adding a new record
		 */
		$sql = "INSERT into cdc_ContactClientInsurance (
				MemberID,
				InsPublic,
				InsPrivate,
				InsNone,
				Concerns,
				Response,
				DateUpdate,
				Userid
				) values (
				'$memberID',
				'$insPublic',
				'$insPrivate',
				'$insNone',
				'$concerns',
				'$response',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'
				)";		
	}
	$result = mysql_db_query($dbname,$sql);
}

function saveClientInfoHealthcare($phpJSON,$memberID) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$concerns   = fieldToDB($phpArray['healthConcerns']);
	$response   = fieldToDB($phpArray['healthResponse']);
		
	/*
	 * Check for existing record for this memberID
	 */
	$sqlCheck = "SELECT EntryID from cdc_ContactClientHealthcare
				 WHERE MemberID = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	
	if (mysql_num_rows($resultCheck)>0) {
		/*
		 * We are updating an existing record
		 */
		$sql = "UPDATE cdc_ContactClientHealthcare
				SET
				Concerns   = '$concerns',
				Response   = '$response',
				DateUpdate = '".date('Y-m-d')."'
				WHERE MemberID = '$memberID'";
	} else {
		/*
		 * We are adding a new record
		 */
		$sql = "INSERT into cdc_ContactClientHealthcare (
				MemberID,
				Concerns,
				Response,
				DateUpdate,
				Userid
				) values (
				'$memberID',
				'$concerns',
				'$response',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'
				)";		
	}
	$result = mysql_db_query($dbname,$sql);
}

function saveClientInfoSocial($phpJSON,$memberID) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$concerns   = fieldToDB($phpArray['socialConcerns']);
	$response   = fieldToDB($phpArray['socialResponse']);
		
	/*
	 * Check for existing record for this memberID
	 */
	$sqlCheck = "SELECT EntryID from cdc_ContactClientSocial
				 WHERE MemberID = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	
	if (mysql_num_rows($resultCheck)>0) {
		/*
		 * We are updating an existing record
		 */
		$sql = "UPDATE cdc_ContactClientSocial
				SET
				Concerns   = '$concerns',
				Response   = '$response',
				DateUpdate = '".date('Y-m-d')."'
				WHERE MemberID = '$memberID'";
	} else {
		/*
		 * We are adding a new record
		 */
		$sql = "INSERT into cdc_ContactClientSocial (
				MemberID,
				Concerns,
				Response,
				DateUpdate,
				Userid
				) values (
				'$memberID',
				'$concerns',
				'$response',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'
				)";		
	}
	$result = mysql_db_query($dbname,$sql);
}

function saveClientInfoSchoolTrans($phpJSON,$memberID) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$iepClass1       = $phpArray['iepClass1'];
	$iepClass2       = $phpArray['iepClass2'];
	$spedDesignation = $phpArray['spedDesignation'];
	$diplomaType     = $phpArray['diplomaType'];
	$freeLunch       = $phpArray['freeLunch'];
	$lowLit          = $phpArray['lowLit'];
	$concerns        = fieldToDB($phpArray['schoolConcerns']);
	$response        = fieldToDB($phpArray['schoolResponse']);
		
	/*
	 * Check for existing record for this memberID
	 */
	$sqlCheck = "SELECT EntryID from cdc_ContactClientSchoolTrans
				 WHERE MemberID = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	
	if (mysql_num_rows($resultCheck)>0) {
		/*
		 * We are updating an existing record
		 */
		$sql = "UPDATE cdc_ContactClientSchoolTrans
				SET
					IEPClass1        = '$iepClass1',
					IEPClass2        = '$iepClass2',
					SPEDDesignation  = '$spedDesignation',
					DiplomaType      = '$diplomaType',
					FreeReducedLunch = '$freeLunch',
					LowLit           = '$lowLit',
					Concerns         = '$concerns',
					Response         = '$response',
					DateUpdate       = '".date('Y-m-d')."'				
				WHERE MemberID = '$memberID'";
	} else {
		/*
		 * We are adding a new record
		 */
		$sql = "INSERT into cdc_ContactClientSchoolTrans (
				MemberID,
				IEPClass1,
				IEPClass2,
				SPEDDesignation,
				DiplomaType,
				FreeReducedLunch,
				LowLit,
				Concerns,
				Response,
				DateUpdate,
				Userid
				) values (
				'$memberID',
				'$iepClass1',
				'$iepClass2',
				'$spedDesignation',
				'$diplomaType',
				'$freeLunch',
				'$lowLit',
				'$concerns',
				'$response',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'
				)";		
	}
	$result = mysql_db_query($dbname,$sql);	
}

function saveClientInfoFamily($phpJSON,$memberID) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$lowIncome = $phpArray['lowIncome'];
	$concerns  = fieldToDB($phpArray['familyConcerns']);
	$response  = fieldToDB($phpArray['familyResponse']);
		
	/*
	 * Check for existing record for this memberID
	 */
	$sqlCheck = "SELECT EntryID from cdc_ContactClientFamily
				 WHERE MemberID = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	
	if (mysql_num_rows($resultCheck)>0) {
		/*
		 * We are updating an existing record
		 */
		$sql = "UPDATE cdc_ContactClientFamily
				SET
					LowIncome  = '$lowIncome',
					Concerns   = '$concerns',
					Response   = '$response',
					DateUpdate = '".date('Y-m-d')."'				
				WHERE MemberID = '$memberID'";
	} else {
		/*
		 * We are adding a new record
		 */
		$sql = "INSERT into cdc_ContactClientFamily (
				MemberID,
				LowIncome,
				Concerns,
				Response,
				DateUpdate,
				Userid
				) values (
				'$memberID',
				'$lowIncome',
				'$concerns',
				'$response',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'
				)";		
	}
	$result = mysql_db_query($dbname,$sql);
}

function saveClientInfoEvents($eventID,$memberID) {
     global $dbname, $db, $db_selected;

     /*
      * See if this member is already registered for this event
      */
     $sql = "SELECT *
               FROM cdc_linkEventMember
               WHERE EventID = '$eventID' AND MemberID = '$memberID'";
     $result = mysql_db_query($dbname,$sql);

     if (mysql_num_rows($result)<1) {
          $sql = "INSERT into cdc_linkEventMember (
                    EventID,
                    MemberID,
                    DateRegister
                    ) values (
                    '$eventID',
                    '$memberID',
                    '".date('Y-m-d G:i:s')."'
                    )";
          $result = mysql_db_query($dbname,$sql);
          return $memberID;
     } else {
          return 0;
     }
}

function removeClientInfoEvents($registrationID) {
     global $dbname, $db, $db_selected;

     $sql = "DELETE from cdc_linkEventMember WHERE RegistrationID = '$registrationID'";
     $result = mysql_db_query($dbname,$sql);

     return $registrationID;
}

function saveClientInfoOther($phpJSON,$memberID) {
	global $dbname, $db, $db_selected;
	
	// Decode JSON
	$phpJSON = urldecode(stripslashes($phpJSON));
	$phpArray = Zend_Json::decode($phpJSON);
	
	$concerns   = fieldToDB($phpArray['otherConcerns']);
	$response   = fieldToDB($phpArray['otherResponse']);
		
	/*
	 * Check for existing record for this memberID
	 */
	$sqlCheck = "SELECT EntryID from cdc_ContactClientOther
				 WHERE MemberID = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	
	if (mysql_num_rows($resultCheck)>0) {
		/*
		 * We are updating an existing record
		 */
		$sql = "UPDATE cdc_ContactClientOther
				SET
				Concerns   = '$concerns',
				Response   = '$response',
				DateUpdate = '".date('Y-m-d')."'
				WHERE MemberID = '$memberID'";
	} else {
		/*
		 * We are adding a new record
		 */
		$sql = "INSERT into cdc_ContactClientOther (
				MemberID,
				Concerns,
				Response,
				DateUpdate,
				Userid
				) values (
				'$memberID',
				'$concerns',
				'$response',
				'".date('Y-m-d')."',
				'".$_SESSION['userid']."'
				)";		
	}
	$result = mysql_db_query($dbname,$sql);
}

function associateMemberContact($memberID,$contactID) {
	global $dbname, $db, $db_selected;
	
	// Check for this memberID/contactID combination
	$sqlCheck = "SELECT * from cdc_linkContactMember 
				WHERE 
				ContactID = '$contactID' AND
				MemberID  = '$memberID'";
	$resultCheck = mysql_db_query($dbname,$sqlCheck);
	if (mysql_num_rows($resultCheck)<1) {	
		$sqlAssocMember = "INSERT into cdc_linkContactMember (
							ContactID,
							MemberID
							) values (
							'$contactID',
							'$memberID'
							)";
		$resultAssocMember = mysql_db_query($dbname,$sqlAssocMember);
	}	
}

function toggleEventAttended($regID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_linkEventMember WHERE RegistrationID = '$regID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	
	if ($row['Attended'] == 1) {
		$newState = 0;
	} else {
		$newState = 1;
	}
	
	$sql = "UPDATE cdc_linkEventMember SET Attended = '$newState' WHERE RegistrationID = '$regID'";
	$result = mysql_db_query($dbname,$sql);
	
	return $regID.'|'.$newState;
}

/*
 * GET INFORMATION FOR VIEWING AND EDITING CONTACTS
 */

function getContactMembersInformation($contactID) {
	global $dbname, $db, $db_selected;
	/*
	 * This function pulls all members associated with 
	 * a particular contactID
	 */
	
	$sqlFamilyMembers = "SELECT * from cdc_linkContactMember
							WHERE
							ContactID = '$contactID'
							ORDER BY CMID";
	$resultFamilyMembers = mysql_db_query($dbname,$sqlFamilyMembers);
	if (mysql_num_rows($resultFamilyMembers)>0) {
		$stringJSON   = '({"Members":[';
		while ($value = mysql_fetch_assoc($resultFamilyMembers)) {
			$memberID = $value['MemberID'];
			$stringJSON .= getMemberInformation($memberID,1,0,$contactID,0).',';		
		}
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';		
	} else {
		$stringJSON = 0;
	}	
	return $stringJSON;
}

function getContactGeneralInformation($contactID) {
	global $dbname, $db, $db_selected;
	
	$sql = "SELECT * from cdc_Contacts WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	$row = mysql_fetch_assoc($result);
	
	/*
	 * Convert dates
	 */
	$dateOfContact = new Zend_Date($row['DateofContact'], Zend_Date::ISO_8601, 'en_US');
	$newDate = $dateOfContact->toString('MMM d, Y h:m a');
	$row['DateofContact'] = "$newDate";
	$row['SubjectLine'] = DBToField($row['SubjectLine']);
	/*
	 * Get contact status
	 */
	$statusArray = getStatusInfo($contactID,'contact');
	if (!empty($statusArray[3])) {
		$dateOfClosure = new Zend_Date($statusArray[3], Zend_Date::ISO_8601, 'en_US');
		$newDateOfClosure = $dateOfClosure->toString('MMM d, Y');
	}	
	
	/*
	 * Get user information
	 */
	if ($row['UseridEntry'] == 1000) {
		$row['enteredByStaffName'] = 'Website User';
	} else {
		$staffArray = getStaffInfo($row['UseridEntry']);
		$row['enteredByStaffName'] = $staffArray['StaffFName'].' '.$staffArray['StaffLName'];
	}
	
	$row['statusClassIcon'] = $statusArray[0];
	$row['statusText']      = $statusArray[1].' '.$newDateOfClosure;
	$row['statusClassBox']  = $statusArray[2];
	$row['statusCloseDate'] = $newDateOfClosure;
		
	$stringJSON = Zend_Json::encode($row);
	return $stringJSON;
}

/*
 * CONTACTS FOR GRIDS
 */

function getContactsForGrid($viewPort=null,$start=null,$limit=null,$sort=null,$acdc=null,$paging=null,$searchString=null) {
	global $dbname, $db, $db_selected;
	
	if ( empty($start) && empty($limit) ) {
		$start = $_POST['start'];
		$limit = $_POST['limit'];
	}
	$limitSQL = ' LIMIT '.$start.','.$limit;
	
	$_SESSION['contactLogStart'] = $start;
		
	if (empty($sort)) {
		$sort = 'C.DateofContact';
	}
	if (empty($acdc)) {
		$acdc = 'DESC';
	}
	$origAcDc = $acdc;
	
	if (!empty($searchString)) {
		/*
		 * Get searchString values
		 */
		$searchStringArray = explode('|',$searchString);
		$keyword   = $searchStringArray[0];
		$memberID  = $searchStringArray[1];
		$dateStart = $searchStringArray[2];
		$dateEnd   = $searchStringArray[3];
		if (!empty($keyword)) {
			$whereStringKeyword = " C.SubjectLine LIKE '%$keyword%' AND";			
		}
		if (!empty($memberID)) {
			$joinStringMember  = ' LEFT JOIN cdc_linkContactMember CM ON CM.ContactID = C.ContactID ';
			$whereStringMember = " CM.MemberID = '$memberID' AND";
		}
		if (!empty($dateStart) || !empty($dateEnd)) {
			$dateStart = extDateToMySQL($dateStart);
			$dateEnd   = extDateToMySQL($dateEnd);
			if ( ($dateStart != '0000-00-00') && ($dateEnd != '0000-00-00') ) {
				$whereStringDate = " C.DateofContact >= '$dateStart' AND C.DateofContact <= '$dateEnd' ";
			} elseif ( ($dateStart != '0000-00-00') &&  ($dateEnd == '0000-00-00') ) {
				$whereStringDate = " C.DateofContact >= '$dateStart' ";
			} elseif ( ($dateEnd != '0000-00-00') && ($dateStart == '0000-00-00') ) {
				$whereStringDate = " C.DateofContact <= '$dateEnd' ";
			}
			$whereStringDate .= ' AND ';
		}
		$whereString = $whereStringKeyword.$whereStringMember.$whereStringDate;
	}
		
	if ($_SESSION['level'] == 1) {
		/*
		 * Super administrator result set
		 */
		$sqlContacts = "SELECT 
						C.ContactID,
						C.IDNumber,
						C.DateofContact,
						C.DateofClosure,
						C.SubjectLine,
						C.Status,
						C.ReferralFollowUp,
						C.UseridEntry
					FROM
						cdc_Contacts C
					LEFT JOIN 
						cdc_Users S ON S.StaffID = C.UseridEntry
					$joinStringMember
					WHERE 
						$whereString
						C.OrgFlag = '".$_SESSION['org']."' AND
						C.Temp    = 0                      AND
						C.Deleted = 0
					ORDER BY 
						$sort $acdc";
		$sqlContactsLtd = $sqlContacts.$limitSQL;
	} elseif ($_SESSION['level']>1) {
		/*
		 * General staff result set
		 */
		$sqlContacts = "SELECT 
						C.ContactID,
						C.IDNumber,
						C.DateofContact,
						C.DateofClosure,
						C.SubjectLine,
						C.Status,
						C.ReferralFollowUp,
						C.UseridEntry
					FROM
						cdc_Contacts C
					LEFT JOIN
						cdc_linkStaffContactFollowUp LS ON (LS.ContactID = C.ContactID AND LS.StaffID = '".$_SESSION['userid']."')
					$joinStringMember
					WHERE 
						(
							C.UseridEntry = '".$_SESSION['userid']."' OR
							LS.StaffID = '".$_SESSION['userid']."'    OR
							C.UseridEntry = 1000
						)                                             AND
						$whereString
						C.OrgFlag = '".$_SESSION['org']."'            AND
						C.Temp    = 0                                 AND
						C.Deleted = 0					
					ORDER BY 
						$sort $acdc";
		$sqlContactsLtd = $sqlContacts.$limitSQL;	
	}	
	$resultContacts    = mysql_db_query($dbname,$sqlContacts);
	$resultContactsLtd = mysql_db_query($dbname,$sqlContactsLtd);
	$totalRows         = mysql_num_rows($resultContacts);	
	$totalRowsLtd      = mysql_num_rows($resultContactsLtd);
	
	$totalPages = ceil($totalRows/$limit);
	if ($paging != 1) {
		/*
		 * Switch AcDc
		 */
		if ($acdc == 'DESC') {
			$acdc = 'ASC';
		} else {
			$acdc = 'DESC';
		}
	}	
	
	if ($totalRows>0) {
		/*
		* Create log title
		*/
		$startTitle  = $start+1;
		$limitTitle  = $start+$totalRowsLtd;
		$currentPage = ceil($limitTitle/20); 
		$logTitle = 'Viewing '.$startTitle.'-'.$limitTitle.' of '.$totalRows.' contacts';
		$stringJSON   = '({"TotalRows":'.$totalRows.',"TotalPages":'.$totalPages.',"LogTitle":"'.$logTitle.'","Start":'.$start.',"Limit":'.$limit.',"Sort":"'.$sort.'","AcDc":"'.$acdc.'","OrigAcDc":"'.$origAcDc.'","CurrentPage":"'.$currentPage.'","SearchString":"'.$searchString.'","Contacts":[';
		while ($value = mysql_fetch_assoc($resultContactsLtd)) {
			/*
			 * Staff information
			 */
			if ($value['UseridEntry'] == 1000) {
				$value['StaffFName'] = 'Website';
				$value['StaffLName'] = 'User';
				$value['StaffEmail'] = '';
				$value['StaffPhone'] = '';
			} else {
				$staffArray = getStaffInfo($value['UseridEntry']);
				
				$value['StaffFName'] = $staffArray['StaffFName'];
				$value['StaffLName'] = $staffArray['StaffLName'];
				$value['StaffEmail'] = $staffArray['StaffEmail'];
				$value['StaffPhone'] = $staffArray['StaffPhone'];
			}	
			
			/*
			 * Entry date
			 */
			$dateOfContact = new Zend_Date($value['DateofContact'], Zend_Date::ISO_8601, 'en_US');
			$newDate = $dateOfContact->toString('MMM d, h:m a');
			$value['DateofContact'] = "$newDate";
			
			/*
			 * Closure date
			 */
			if (!empty($value['DateofClosure'])) {
				$dateOfClosure = new Zend_Date($value['DateofClosure'], Zend_Date::ISO_8601, 'en_US');
				$newDate = $dateOfClosure->toString('MMM d, YYYY');
			} else {
				$newDate = '';
			}
			$value['DateofClosure'] = "$newDate";				
			
			/*
			 * Status 
			 */
			$statusArray = getStatusInfo($value['ContactID'],'contact');
			$value['StatusClass']    = $statusArray[0];
			$value['StatusText']     = $statusArray[1];
			$value['StatusRowClass'] = $statusArray[2];
			$value['StatusDiv']      = '<div ext:qtip="'.$statusArray[1].'" class="'.$statusArray[0].'"></div>';
			
			/*
			 * Check for no subject
			 */
			if (empty($value['SubjectLine'])) {
				$value['SubjectLine'] = '[No subject]';
			}
			$value['SubjectDiv'] ='<a href="contactForm.php?contactID='.$value['ContactID'].'" ext:qtip="'.$value['SubjectLine'].'">'.$value['SubjectLine'].'</a>';
			
			/*
			 * Check for other empty fields
			 */
			if (empty($value['StaffPhone'])) {
				$value['StaffPhone'] = '[none]';
			}
			
			$stringJSON .= Zend_Json::encode($value).',';
		}
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';
	} else {
		$stringJSON = 0;	
	}	
	if ($viewPort == 'page') {
		return $viewPort.'~~|~~'.$stringJSON;
	} else {
		return $stringJSON;
	}	
}

function deleteContact($contactID) {
	global $dbname, $db, $db_selected;
	
	/*
	 * Delete cdc_Contacts
	 */
	$sql = "DELETE from cdc_Contacts WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkStaffContactFollowUp
	 */
	$sql = "DELETE from cdc_linkStaffContactFollowUp WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_ContactFollowUp
	 */
	$sql = "DELETE from cdc_ContactFollowUp WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkContactMember
	 */
	$sql = "DELETE from cdc_ContactMember WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkContactLibrary
	 */
	$sql = "DELETE from cdc_ContactLibrary WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkContactEvent
	 */
	$sql = "DELETE from cdc_ContactEvent WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkContactFamily
	 */
	$sql = "DELETE from cdc_ContactFamily WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkContactEvent
	 */
	$sql = "DELETE from cdc_linkContactEvent WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	/*
	 * Delete cdc_linkContactLibrary
	 */
	$sql = "DELETE from cdc_linkContactLibrary WHERE ContactID = '$contactID'";
	$result = mysql_db_query($dbname,$sql);
	
	return $contactID;
}

function contactStatusUpdate($contactID,$newStatus) {
	global $dbname, $db, $db_selected;
	
	if ($newStatus == 'close') {
		$sql = "UPDATE cdc_Contacts 
				SET 
				Status = 3,
				DateofClosure = '".date('Y-m-d')."',
				UseridLastUpdate = '".$_SESSION['userid']."'
				WHERE
				ContactID = '$contactID'
				";
	} elseif ($newStatus == 'update') {
		$sql = "UPDATE cdc_Contacts 
				SET 
				DateUpdate = '".date('Y-m-d')."',
				UseridLastUpdate = '".$_SESSION['userid']."'
				WHERE
				ContactID = '$contactID'
				";
	} elseif ($newStatus == 'reopen') {
		$sql = "UPDATE cdc_Contacts 
				SET 
				Status = 4,
				DateUpdate = '".date('Y-m-d')."',
				UseridLastUpdate = '".$_SESSION['userid']."'
				WHERE
				ContactID = '$contactID'
				";
	}  
	$result = mysql_db_query($dbname,$sql);
	
	return $contactID;
}

function getMembersForExtAutocompleter() {
	global $dbname, $db, $db_selected;
	
	$entry = fieldToDB($_POST['query']);
	$renderType='json';
	
	$orgField = 'Org'.$_SESSION['org'];
	$sql = "SELECT MemberID,FirstName,LastName,City,State
			FROM cdc_ContactClientDemographics
			WHERE
			(FirstName LIKE '%$entry%' OR
			LastName  LIKE '%$entry%') AND
			$orgField = 1
			ORDER BY LastName";		
	$result = mysql_db_query($dbname,$sql);
	$rows = mysql_num_rows($result);
	if ($renderType == 'list') {
		$returnString = '<ul>';
	}
	$stringJSON   = '({"Total":"'.$rows.'","Members":[';
		
	$i=0;
	while ($value = mysql_fetch_assoc($result)) {
		$value['MemberFullName'] = $value['FirstName'].' '.$value['LastName'];
		if ($renderType == 'list') {
								
			if (($i % 2) > 0) { $class = 'blueRow'; }
			else { $class = ''; }	
			$returnString .= '<li class="'.$class.'">'.$subjectLine.' '.$newDate.'</li>';
		}
		$stringJSON .= Zend_Json::encode($value).',';
			
		$i++;
	}
	if ($renderType == 'list') {
		$returnString .= '</ul>';
	} elseif ($renderType == 'json') {
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';
		$returnString = $stringJSON;
	}
	
	return $returnString;
}
/*
 * TODO: Make one autocompleter function for Members
 */
function getContactForAutocompleter() {
	global $dbname, $db, $db_selected;
	
	$entry = fieldToDB($_POST['query']);
	$start = $_POST['start'];
	$limit = $_POST['limit'];
	$renderType='json';
	
	/*
	 * Get all contacts LIKE $entry
	 */
	if ($_SESSION['level'] == 1) {
		$sql = "SELECT ContactID,DateofContact,SubjectLine
				FROM cdc_Contacts 
				WHERE
				SubjectLine LIKE '%$entry%' AND
				Deleted = 0
				ORDER BY SubjectLine";
	} else {
		$sql = "SELECT ContactID,DateofContact,SubjectLine
				FROM cdc_Contacts 
				WHERE
				SubjectLine LIKE '%$entry%' AND
				Deleted = 0 AND
				UseridEntry = ".$_SESSION['userid']."
				ORDER BY SubjectLine";
	}	
	$result = mysql_db_query($dbname,$sql);
	$rows = mysql_num_rows($result);
	if ($renderType == 'list') {
		$returnString = '<ul>';
	}
	$stringJSON   = '({"Total":"'.$rows.'","Contacts":[';
		
	$i=0;
	while ($value = mysql_fetch_assoc($result)) {
		$dateOfContact = new Zend_Date($value['DateofContact'], Zend_Date::ISO_8601, 'en_US');
		$newDate = $dateOfContact->toString('MMM d, h:m a');
		$value['DateofContact'] = "$newDate";
		if ($renderType == 'list') {
			$contactID   = $value['ContactID'];
			$subjectLine = $value['SubjectLine'];
								
			if (($i % 2) > 0) { $class = 'blueRow'; }
			else { $class = ''; }	
			$returnString .= '<li class="'.$class.'">'.$subjectLine.' '.$newDate.'</li>';
		}
		$stringJSON .= Zend_Json::encode($value).',';
			
		$i++;
	}
	if ($renderType == 'list') {
		$returnString .= '</ul>';
	} elseif ($renderType == 'json') {
		$stringJSON = substr($stringJSON,0,-1);
		$stringJSON .= ']})';
		$returnString = $stringJSON;
	}
	
	echo $returnString;
}
?>